import React, { Component, PropTypes } from 'react';
import { Spin, Form, Row, Col, Affix, Button, message } from "antd";
import { deepFullCopy, messages } from "share/common";
import { connect } from 'react-redux';
import menuRoute from "routes/menuRoute";
import customField from "share/customField";
import contractService from 'containers/contract/contract.service';
import Chooser from "components/chooser";
import moment from "moment";

const FormItem = Form.Item;

class NewContractV2 extends Component {

  state = {
    loading: false,
    contractType: {}, //合同类型
    formInfo: {}, //表单配置
    formDefaultValue: [], //表单默认值
    editFormValues: [], //编辑时的表单数据
    relatedApplication: [], //关联申请单,
    contractInfo: {},
    jobInfo: {}
  };

  rowLayout = { type: 'flex', gutter: 24, justify: 'center' };

  formItemLayout = {
    labelCol: {
      xs: { span: 14 },
      sm: { span: 8 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 16 },
    }
  };

  componentDidMount () {
    this.setState({ loading: true });
    Promise.all([this.getFormInfo(), this.getContractType(), this.getJobInfo()]).finally(() => {
      this.setState({ loading: false });
    });
  };

  //是否为创建
  isNew = () => !this.props.params.entityOID;

  getJobId = () => {
    const { companyWithUserJobsDTOList } = this.props.user;
    return companyWithUserJobsDTOList ? companyWithUserJobsDTOList[0].userJobsDTOList[0].id : ''
  };

  //获取岗位详情
  getJobInfo = () => {
    let jobId = this.getJobId();
    contractService.getJobInfo(jobId).then(res => {
      this.setState({jobInfo: res.data})
    });
  }

  getFormInfo = () => {
    const { formOID } = this.props.params;
    contractService.getCustomForm(formOID).then(res => {
      this.setState({
        formInfo: res.data,
      }, () => {
        if (this.isNew()) {
          this.getFormDefaultValue()
        } else {
          this.getContractHeaderInfo()
        }
      })
    }).catch(err => {
      message.error(err.response.data.message);
    })
  };

  //获取合同头信息
  getContractHeaderInfo = () => {
    contractService.getContractHeaderInfoV2(this.props.params.entityOID).then(res => {
      let relatedApplication = [];
      res.data.applicationOID && relatedApplication.push({
        businessCode: res.data.applicationBusinessCode,
        applicationOID: res.data.applicationOID
      })
      this.setState({
        editFormValues: res.data.customFormValues,
        relatedApplication,
        contractInfo: res.data
      });
    })
  };

  //新建时获取并设置默认值
  getFormDefaultValue = () => {
    const { userOID } = this.props.user;
    const { formOID } = this.props.params;
    const { formInfo } = this.state;
    let jobId = this.getJobId()
    contractService.getFormValue({ userOID, formOID, jobId }).then(res => {
      formInfo.customFormFields.map(item => {
        let _item = res.data.find(value => item.fieldOID === value.fieldOID);
        if (_item) {
          item.value = _item.value;
        }
        return item;
      });
      this.setState({
        formDefaultValue: res.data,
        formInfo
      })
    })
  };

  //根据合同类型id获取合同类型
  getContractType = () => {
    const { company, params } = this.props;
    contractService.getContractTypeInfo(company.setOfBooksId, params.contractTypeId).then(res => {
      this.setState({ contractType: res.data});
    }).catch(err => {
      message.error(err.response.data.message);
    })
  };

  //处理是否启用时间
  processEnableTime = field => {
    let enableTime = false;
    if (field.fieldConstraint && JSON.parse(field.fieldConstraint) && JSON.parse(field.fieldConstraint).enableTime) {
      enableTime = true;
    }
    return enableTime;
  };

  formatDateToLocal = (date) => {
    return moment(date).local().format('YYYY-MM-DDTHH:mm:ss') + 'Z'
  };

  //处理启用时间默认值
  handleDefaultStartDate = field => {
    let defaultTime;
    if (field.fieldConstraint && JSON.parse(field.fieldConstraint)) {
      if (JSON.parse(field.fieldConstraint).defaultTime) {
        defaultTime = moment(moment(JSON.parse(field.fieldConstraint).defaultTime).format('HH:mm'), 'HH:mm');
      } else {
        if (field.messageKey === 'start_date') {
          defaultTime = moment('00:00', 'HH:mm');
        }
        if (field.messageKey === 'end_date') {
          defaultTime = moment('23:59', 'HH:mm');
        }
      }
    }
    return defaultTime;
  };

  //根据formInfo渲染控件
  renderCustom = (field) => {
    const { form } = this.props;
    const { getFieldDecorator, getFieldsValue } = form;
    const { formDefaultValue, formInfo, jobInfo, contractInfo } = this.state;
    let fieldDefaultValue = {};
    let label = field.fieldName;
    let customFormFields = this.isNew() ? formInfo.customFormFields : contractInfo.customFormValues;
    let rangePickerInitialValue = [];
    this.isNew() && formDefaultValue.map(item => {
      if (field.fieldOID === item.fieldOID) {
        fieldDefaultValue = item
      }
    });
    if (field.messageKey === 'number') {
      JSON.parse(field.fieldContent || '{}').unit && (label = `${field.fieldName}(${JSON.parse(field.fieldContent || '{}').unit})`);
    }
    if (field.messageKey === 'start_date') {
      let startName = field.fieldName;
      let endName = '';
      customFormFields.map(item => {
        if (item.messageKey === 'end_date') {
          endName = item.fieldName
          rangePickerInitialValue = [
            customField.getInitialValue(field),
            customField.getInitialValue(item)
          ]
        }
      });
      //开始结束日期都启用时间时，该组件才启用时间
      if (this.processEnableTime(field)) {
        field.defaultValueTime = [];
        field.defaultValueTime.push(this.handleDefaultStartDate(field));
        customFormFields.map(fieldItem => {
          if (fieldItem.messageKey === 'end_date' && this.processEnableTime(fieldItem)) {
            field.defaultValueTime.push(this.handleDefaultStartDate(fieldItem));
            field.enableTime = true
          }
        })
      }
      field.messageKey = 'range_picker';
      label = startName + '-' + endName;
      field.promptInfoList = [startName, endName];
    }
    //编辑时不可以修改公司和币种
    if (!this.isNew() && (field.messageKey === 'currency_code' || field.messageKey === 'select_company')) field.isReadOnly = true;
    if (field.hide || field.messageKey === 'end_date') return;
    return (
      <Row {...this.rowLayout} key={field.fieldOID}>
        <Col span={12}>
          <FormItem
            label={label || ' '}
            {...this.formItemLayout}
            colon={!!label}
          >
            {getFieldDecorator(field.fieldOID, {
              rules: [{
                required: field.required,
                message: messages('common.can.not.be.empty', { arg1: field.fieldName })/*{arg1} 不能为空*/
              }],
              initialValue:
                this.isNew()
                  ? customField.getDefaultValue(field, fieldDefaultValue)
                  : field.messageKey === 'range_picker'
                  ? rangePickerInitialValue
                  : customField.getInitialValue(field)
            })(
              customField.renderForm({
                field,
                jobId: this.getJobId(),
                formValues: getFieldsValue(),
                form: this.props.form,
                formDetail: formInfo,
                jobInfo
              })
            )}
          </FormItem>
        </Col>
      </Row>
    )
  };

  renderApplication = () => {
    const { formInfo, relatedApplication } = this.state;
    const { form } = this.props;
    const { customFormPropertyMap = {} } = formInfo;
    const relatedApplicationProperty = JSON.parse(customFormPropertyMap['related.application.property']);
    const { getFieldDecorator } = form;
    const { formOID } = this.props.params;
    return (
      <Row {...this.rowLayout}>
        <Col span={12}>
          <FormItem label={messages('finance-9.key76')/*关联申请单*/} {...this.formItemLayout}>
            {getFieldDecorator('application', {
              initialValue: relatedApplication,
              rules: [{
                required: relatedApplicationProperty.required,
                message: messages('common.name.is.required', { arg1: messages('finance-9.key76')/*关联申请单*/ })
              }]
            })(
              <Chooser
                type='available_corporate_request'
                labelKey='businessCode'
                valueKey='applicationOID'
                listExtraParams={{
                  formOID,
                  expenseReportCompanyOID: this.props.company.companyOID
                }}
                itemMap
                single
                disabled={!this.isNew()}
              />
            )}
          </FormItem>
        </Col>
      </Row>
    )
  };

  handleSave = () => {
    const { contractType: { contractCategory }, contractInfo, formInfo } = this.state;
    const { userOID } = this.props.user;
    const { contractTypeId } = this.props.params;
    let params = {};
    let customFormFields = deepFullCopy(this.isNew() ? formInfo.customFormFields : contractInfo.customFormValues);
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        params.applicantOid = userOID;
        params.contractTypeId = contractTypeId;
        params.contractCategory = contractCategory;
        if(values.application && values.application[0]){
          params.applicationOID = values.application[0].applicationOID;
          params.applicationBusinessCode = values.application[0].businessCode;
        }
        params.customFormValues = this.handleValues(values);
        params.customFormValues.map((item, index) => {/*保存前需要要将控件range_picker拆分分为开始日期／结束日期控件*/
          item.messageKey === "start_date" && customFormFields.map(fieldItem => {
            if (fieldItem.messageKey === "end_date") {
              if (item.value) {
                let rangePickerValue = deepFullCopy(item.value);
                if (this.processEnableTime(item) && this.processEnableTime(fieldItem)) {
                  item.value = this.formatDateToLocal(rangePickerValue[0]);
                  fieldItem.value = this.formatDateToLocal(rangePickerValue[1]);
                } else {
                  item.value = this.formatDateToLocal(moment(rangePickerValue[0]).format("YYYY-MM-DD 00:00:00"));
                  fieldItem.value = this.formatDateToLocal(moment(rangePickerValue[1]).format("YYYY-MM-DD 23:59:59"));
                }
              }
              if (!item.value) {
                item.value = undefined;
                fieldItem.value = undefined;
              }
              params.customFormValues.splice(index + 1, 1, fieldItem)
            }
          })
        })
        //编辑时需要传id和versionNumber
        if (!this.isNew()) {
          params.id = contractInfo.id;
          params.versionNumber = contractInfo.versionNumber
        }
        let serviceName = this.isNew() ? 'newContractHeader' : 'updateContractHeader';
        this.setState({ loading: true });
        contractService[serviceName](params).then(res => {
          if (res.status === 200){
            this.setState({ loading: false });
            let documentOid = this.isNew() ? res.data.documentOid : contractInfo.documentOid;
            message.success(messages('common.save.success',{arg1: ''})/*{arg1} 保存成功*/);
            this.context.router.push(menuRoute.getRouteItem('contract-detail', 'key').url.replace(':entityOID', documentOid).replace(':entry', 'my'));
          }
        }).catch(() => {
          this.setState({ loading: false });
          message.error(messages('common.save.filed')/*保存失败*/);
        })
      }
    })
  };

  handleValues = values => {
    const { customFormFields} = this.state.formInfo;
    const { editFormValues } = this.state;
    let deepCloneFields = deepFullCopy(this.isNew() ? customFormFields : editFormValues);
    deepCloneFields.map(item => {
      Object.keys(values).map(key => {
        if (key === item.fieldOID || key === item.formValueOID) {
          item = customField.formatFormValue(item, values[key]);
        }
      })
    });
    return deepCloneFields;
  };

  //取消
  onCancel = () => {
    this.context.router.push(menuRoute.getRouteItem('my-contract', 'key').url);
  };

  render () {
    const { loading, formInfo, editFormValues } = this.state;
    const { customFormFields = [], customFormPropertyMap = {} } = formInfo;
    const renderCustomFormFields = deepFullCopy(this.isNew() ? customFormFields : editFormValues);
    const relatedApplicationProperty = JSON.parse(customFormPropertyMap['related.application.property'] || '{}');
    return (
      <div className="new-contract" style={{ marginBottom: '50px' }}>
        <Spin spinning={loading}>
          <Form>
            {relatedApplicationProperty.enable && this.renderApplication()}
            {renderCustomFormFields.map(field => this.renderCustom(field))}
          </Form>
        </Spin>
        <Affix offsetBottom={0} className="bottom-bar">
          <Button type="primary" loading={loading} onClick={this.handleSave} style={{ margin: '0 20px' }}>
            {messages('finance-6.key96')/*下一步*/}
          </Button>
          <Button onClick={this.onCancel}>{messages('common.cancel')/*取消*/}</Button>
        </Affix>
      </div>
    )
  }
}

NewContractV2.contextTypes = {
  router: PropTypes.object
};

function mapStateToProps (state) {
  return {
    user: state.login.user,
    company: state.login.company
  }
}

const NewContractV2Comp = Form.create()(NewContractV2);

export default connect(mapStateToProps)(NewContractV2Comp);
